package com.lixinxinlove.jaychoumusic

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.*
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import android.widget.RemoteViews
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.core.app.NotificationCompat.*
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.lixinxinlove.jaychoumusic._interface.IMusicPlay
import com.lixinxinlove.jaychoumusic.service.MusicPlayService
import java.lang.Exception


private const val TYPE_START=1
private const val TYPE_STOP= 0

class NotificationActivity : AppCompatActivity() {

    private lateinit var btn1: AppCompatButton
    private lateinit var btn2: AppCompatButton
    private lateinit var btn3: AppCompatButton


    private val list: MutableList<String> = mutableListOf<String>()


    private lateinit var dynamicReceiver: CustomNotificationBroadcastReceiver


    private lateinit var iMusicPlay: IMusicPlay

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_notification)

        // createNotificationChannel("chat", "chat", 1)
        //  createNotificationChannel("subscribe", "subscribe", 2)
        //  createNotificationChannel("cost", "cost", 2)


        //实例化IntentFilter对象
        val filter = IntentFilter()
        filter.addAction("notification_play")
        dynamicReceiver = CustomNotificationBroadcastReceiver()
        //注册广播接收
        registerReceiver(dynamicReceiver, filter)



        btn1 = findViewById(R.id.btn1)
        btn2 = findViewById(R.id.btn2)
        btn3 = findViewById(R.id.btn3)

        btn1.setOnClickListener {
            //sendChatMsg()

            startActivity(Intent(this,CountdowntimerListActivity::class.java))
        }
        btn2.setOnClickListener {
            sendSubscribeMsg()
        }

        btn3.setOnClickListener {
            // compostNotification()

            showNotification()

            bindService()
        }


    }


    //判断通知是否启用
    private fun isNotificationEnabled(context: Context): Boolean {
        var isOpened = false
        isOpened = try {
            NotificationManagerCompat.from(context).areNotificationsEnabled()
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
        return isOpened
    }


    private fun createNotificationChannel(channelId: String, channelName: String, importance: Int) {
        val channel = NotificationChannel(channelId, channelName, importance)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            channel.setAllowBubbles(true)
        }
        val notificationManager: NotificationManager =
            getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }


    fun sendChatMsg() {
        val manager: NotificationManager =
            getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val notification: Notification = Builder(this, "chat")
            .setContentTitle("收到一条聊天消息")
            .setContentText("今天中午吃什么？")
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    resources,
                    R.drawable.ic_launcher_background
                )
            )
            .setAutoCancel(true)
            .build()
        manager.notify(1, notification)
    }

    fun sendSubscribeMsg() {
        val manager: NotificationManager =
            getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val notification: Notification = Builder(this, "subscribe")
            .setContentTitle("收到一条订阅消息")
            .setContentText("地铁沿线30万商铺抢购中！")
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    resources,
                    R.drawable.ic_launcher_background
                )
            )
            .setAutoCancel(true)
            .setNumber(2)
            .build()
        manager.notify(2, notification)
    }

    @SuppressLint("RemoteViewLayout")
    fun compostNotification() {


        val pendingIntent =
            PendingIntent.getActivity(
                this,
                0,
                Intent(this, MainActivity::class.java),
                PendingIntent.FLAG_CANCEL_CURRENT
            )

        //自定义的布局视图
        val notificationLayout: RemoteViews =
            RemoteViews(packageName, R.layout.view_notification_layout)

        notificationLayout.setTextViewText(R.id.not_title, "这是一个推送过来的标题")

        //val notificationLayoutExpanded = RemoteViews(packageName, R.layout.view_notification_layout)

        val manager: NotificationManager =
            getSystemService(NOTIFICATION_SERVICE) as NotificationManager

        val notification: Notification = Builder(this, "cost")
            //.setStyle(NotificationCompat.DecoratedCustomViewStyle())
            .setPriority(PRIORITY_DEFAULT)
            .setAutoCancel(true)//点击通知栏的时候移除通知栏
            .setContentTitle("contentTitle")
            .setContentText("contenttext")
            .setContentIntent(pendingIntent)//跳转到指定的页面
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setOngoing(false)//设置true表示是一个正在活动的后台任务，不会被清除掉，比如音乐播放器
            .setWhen(System.currentTimeMillis())
            .setCustomContentView(notificationLayout)
            .build()

        manager.notify(3, notification)
    }


    /**
     * 展示通知栏
     */
    private lateinit var notification: Notification

    private fun showNotification() {

        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val NOTIFICATION_ID = 10003
        val id = "channel_demo"

        val mChannel = NotificationChannel(id, "app_name", NotificationManager.IMPORTANCE_LOW)
        mChannel.description = "通知栏"
        mChannel.enableLights(false)
        mChannel.lightColor = Color.BLUE
        mChannel.enableVibration(true)
        mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
        notificationManager.createNotificationChannel(mChannel)


        notification = Builder(this, id)
            .setSmallIcon(R.mipmap.ic_logo)
            .setWhen(System.currentTimeMillis())
            //.setStyle(DecoratedCustomViewStyle())
            .setContentIntent(getDefaultIntent(Notification.FLAG_ONGOING_EVENT))
            .setCustomContentView(getContentView(false))
            //.setCustomBigContentView(getContentView(true))
            .setPriority(PRIORITY_HIGH)
            .setTicker("正在播放")
            .setOngoing(true)
            .setChannelId(mChannel.id)
            .build()

        notificationManager.notify(NOTIFICATION_ID, notification)
    }

    private fun getDefaultIntent(flags: Int): PendingIntent? {
        return PendingIntent.getActivity(this, 1, Intent(this, MainActivity::class.java), flags)
    }


    private fun getContentView(showBigView: Boolean): RemoteViews {
        val remoteViews = RemoteViews(
            packageName,
            if (showBigView) R.layout.view_notify_big else R.layout.view_notify_small
        )
        remoteViews.setTextViewText(R.id.title_text, "自定义标题")
        remoteViews.setTextViewText(R.id.desc_text, "描述的部分")
        remoteViews.setImageViewResource(R.id.logo_image, R.mipmap.ic_logo)


        val intent = Intent("notification_play")
        intent.putExtra("type", 1)
        val pendingPlayIntentClick =
            PendingIntent.getBroadcast(this, 11, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        remoteViews.setOnClickPendingIntent(R.id.image_play, pendingPlayIntentClick) //播放按钮的点击事件
        return remoteViews
    }


    inner class CustomNotificationBroadcastReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            val type = intent.getIntExtra("type", -1)
            if (type == 1) {
                Toast.makeText(context, "暂停", Toast.LENGTH_LONG).show()
                Log.e("NotificationActivity", "type=$type")
                iMusicPlay.stop()
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(dynamicReceiver)
        unBindService()
    }

    private fun bindService() {
        val bindIntent = Intent(this, MusicPlayService::class.java)
        startService(bindIntent)
        bindService(bindIntent, serviceConnection, BIND_ABOVE_CLIENT)
    }


    private fun unBindService() {
        unbindService(serviceConnection)
        val bindIntent = Intent(this, MusicPlayService::class.java)
        stopService(bindIntent)
    }



    private val serviceConnection = object : ServiceConnection {

        @SuppressLint("SetTextI18n")
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            iMusicPlay = service as MusicPlayService.MyBinder
            iMusicPlay.play()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            //取消绑定服务
        }
    }


}